﻿using System.Configuration;
using System.Transactions;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.DAL;
using Lucene.Net.Analysis.CJK;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using FSDirectory = Lucene.Net.Store.FSDirectory;

namespace Ledict.ConditionExtract.BLL
{
    /// <summary>
    /// 索引创建业务逻辑
    /// </summary>
    public class LuceneCreate
    {
        DefusePrivacy defuseprivacy = new DefusePrivacy();

        static string indexPath = System.IO.Path.Combine(ConfigurationManager.AppSettings["luceneRoot"]);
        //static string indexPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Expressluceneindex\");

        internal static readonly DirectoryInfo INDEX_DIR = new DirectoryInfo(indexPath);
        static CJKAnalyzer analyzer = new CJKAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
        CreateIndexDAL createIndex = new CreateIndexDAL();
        private int _resultCount;
        public int ResultCount
        {
            get { return _resultCount; }
            set { _resultCount = value; }
        }

        ParagraphToSentenceBLL paragraphtosentence = new ParagraphToSentenceBLL();
        //NewIDBLL newid = new NewIDBLL();
        IndexWriter writer;

        public List<string> HeadWords = new List<string>();//多个案由
        public int MaxCount = 0;
        public ProcessShow processShow;   //进度显示更新

        public LuceneCreate()
        {


        }
        /// <summary>
        /// 开始建表述索引(分句)
        /// </summary>
        public void CreateIndex()
        {
            bool isCreate = !IndexReader.IndexExists(FSDirectory.Open(INDEX_DIR));
            writer = new IndexWriter(FSDirectory.Open(INDEX_DIR), analyzer, isCreate, IndexWriter.MaxFieldLength.UNLIMITED);

            try
            {
                //需要建立索引的数据
                DataTable Casedt = createIndex.GetIndex(HeadWords); //案例
                DataTable Paradt;
                DataTable dtHeadWord;
                string ParagraphText = "";
                int ParagraphTypeId = 0;
                List<string> returnDic = new List<string>();


                //统计本次写入文件的索引数目
                if (Casedt.Rows.Count > 0)
                {
                    using (var tran = new TransactionScope())
                    {

                        #region 写索引

                        //建立索引字段
                        foreach (DataRow dr in Casedt.Rows)
                        {
                            Paradt = createIndex.GetParagraph(dr["CaseId"].ToString()); //逻辑段
                            dtHeadWord = createIndex.GetHeadWords(dr["CaseID"].ToString()); //当前案例关联的所有案由
                            foreach (DataRow dp in Paradt.Rows)
                            {
                                ParagraphText = dp["ParagraphText"].ToString();
                                ParagraphTypeId = Convert.ToInt32(dp["ParagraphTypeId"].ToString()); //逻辑段140或150
                                returnDic = paragraphtosentence.GetSentence(ParagraphText, ParagraphTypeId); //分句

                                #region 句

                                foreach (string key in returnDic)
                                {
                                    Document doc = new Document();
                                    //添加doc  
                                    doc.Add(new Field("SentenceId", Guid.NewGuid().ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("SentenceTime", DateTime.Now.ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("Sentence", key, Field.Store.YES, Field.Index.ANALYZED)); //句
                                    doc.Add(new Field("ParagraphTypeId", ParagraphTypeId.ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED)); //段150
                                    doc.Add(new Field("CaseId", dr["CaseID"].ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED)); //caseid
                                    doc.Add(new Field("PropertyId", dr["PropertyId"].ToString(), Field.Store.NO,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("JudicialProcedureId", dr["JudicialProcedureId"].ToString(),
                                        Field.Store.NO, Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("CourtId", dr["CourtId"].ToString(), Field.Store.NO,
                                        Field.Index.NOT_ANALYZED));
                                    //案由
                                    for (int k = 0; k < dtHeadWord.Rows.Count; k++)
                                    {
                                        doc.Add(new Field("AllParentID",
                                            dtHeadWord.Rows[k]["HW_AllParentIDs"].ToString(), Field.Store.NO,
                                            Field.Index.NOT_ANALYZED));
                                    }
                                    writer.AddDocument(doc);
                                }

                                #endregion
                            }

                            createIndex.UpdateIndexStatus(int.Parse(dr["CaseId"].ToString()));
                            _resultCount++;
                            processShow(MaxCount, _resultCount);

                        }

                        writer.Optimize();
                        writer.Commit();
                        writer.Dispose();
                        tran.Complete();

                        if (_resultCount < MaxCount) //循环
                        {
                            CreateIndex();
                        }
                        else //不循环
                        {
                            _resultCount = MaxCount + 1;
                            processShow(MaxCount, _resultCount); //已完成
                            writer.Close();


                        }

                        #endregion

                    }
                }
                else //不循环
                {
                    _resultCount = MaxCount + 1;
                    processShow(MaxCount, _resultCount); //已完成
                    writer.Close();
                }





            }
            catch (Exception ex)
            {
                AddLog.WriteLog(ex, "");
            }
            finally
            {
                writer.Dispose();
            }
        }





        //public void CreateIndex_People()
        //{
        //    try
        //    {
        //        //需要建立索引的数据

        //        DataTable Casedt = createIndex.GetIndex(HeadWords);//案例
        //        DataTable Paradt;
        //        DataTable dtHeadWord;
        //        string ParagraphText = "";
        //        int ParagraphTypeId = 0;
        //        List<string> returnDic = new List<string>();
        //        //统计本次写入文件的索引数目

        //        if (Casedt.Rows.Count > 0)
        //        {
        //            #region 写索引
        //            //建立索引字段
        //            foreach (DataRow dr in Casedt.Rows)
        //            {
        //                Paradt = createIndex.GetParagraph(dr["CaseId"].ToString());//逻辑段
        //                dtHeadWord = createIndex.GetHeadWords(dr["CaseID"].ToString());
        //                foreach (DataRow dp in Paradt.Rows)
        //                {
        //                    ParagraphText = dp["ParagraphText"].ToString().Replace("\r", "").Replace("\n", "");
        //                    ParagraphTypeId = Convert.ToInt32(dp["ParagraphTypeId"].ToString());
        //                    returnDic = paragraphtosentence.GetSentence(ParagraphText, ParagraphTypeId);//分句
        //                    #region 句
        //                    foreach (string key in returnDic)
        //                    {
        //                        Document doc = new Document();
        //                        //添加doc  
        //                        doc.Add(new Field("SentenceId", Guid.NewGuid().ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        //                        doc.Add(new Field("SentenceTime", DateTime.Now.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        //                        doc.Add(new Field("Sentence", key, Field.Store.YES, Field.Index.ANALYZED));   //句
        //                        doc.Add(new Field("ParagraphTypeId", ParagraphTypeId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//段150
        //                        doc.Add(new Field("CaseId", dr["CaseID"].ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); //caseid
        //                        doc.Add(new Field("PropertyId", dr["PropertyId"].ToString(), Field.Store.NO, Field.Index.NOT_ANALYZED));
        //                        doc.Add(new Field("JudicialProcedureId", dr["JudicialProcedureId"].ToString(), Field.Store.NO, Field.Index.NOT_ANALYZED));
        //                        doc.Add(new Field("CourtId", dr["CourtId"].ToString(), Field.Store.NO, Field.Index.NOT_ANALYZED));
        //                        //案由
        //                        for (int k = 0; k < dtHeadWord.Rows.Count; k++)
        //                        {
        //                            doc.Add(new Field("AllParentID", dtHeadWord.Rows[k]["HW_AllParentIDs"].ToString(), Field.Store.NO, Field.Index.NOT_ANALYZED));
        //                        }
        //                        writer.AddDocument(doc);
        //                    }
        //                    #endregion
        //                }

        //                createIndex.UpdateIndexStatus(int.Parse(dr["CaseId"].ToString()));
        //                ResultCount++;
        //                processShow(MaxCount, ResultCount);

        //            }

        //            writer.Optimize();
        //            writer.Commit();
        //            if (ResultCount < MaxCount)//循环
        //            { CreateIndex_People(); }
        //            else //不循环
        //            {
        //                ResultCount = MaxCount + 1;
        //                processShow(MaxCount, ResultCount);//已完成
        //                writer.Close();
        //            }
        //            #endregion
        //        }
        //        else  //不循环
        //        {
        //            ResultCount = MaxCount + 1;
        //            processShow(MaxCount, ResultCount);//已完成
        //            writer.Close();
        //        }


        //    }
        //    catch (Exception error)
        //    {

        //    }


        //}

        /// <summary>
        /// 统计总数
        /// </summary>
        /// <returns></returns>
        public int GetSumCount(List<string> headWords)
        {
            return createIndex.GetSumCount(headWords);//逻辑段数据 top 5000
        }


        #region 案例

        /// <summary>
        /// 统计总数
        /// </summary>
        /// <returns></returns>
        public int GetCaseSumCount(int cateGoryId)
        {
            return createIndex.GetCaseSumCount(cateGoryId);//逻辑段数据 top 5000
        }


        /// <summary>
        /// 开始建表述索引(分句),通过案例
        /// </summary>
        public void CreateCaseIndex(int cateGoryId)
        {

            bool isCreate = !IndexReader.IndexExists(FSDirectory.Open(INDEX_DIR));
            writer = new IndexWriter(FSDirectory.Open(INDEX_DIR), analyzer, isCreate, IndexWriter.MaxFieldLength.UNLIMITED);
            try
            {
                //需要建立索引的数据
                DataTable casedt = createIndex.GetCaseIndex(cateGoryId); //案例
                DataTable Paradt;


                //统计本次写入文件的索引数目
                if (casedt.Rows.Count > 0)
                {
                    using (var tran = new TransactionScope())
                    {

                        #region 写索引

                        //建立索引字段
                        foreach (DataRow dr in casedt.Rows)
                        {
                            Paradt = createIndex.GetParagraph(dr["CaseId"].ToString()); //逻辑段
                            DataTable dtHeadWord = createIndex.GetHeadWords(dr["CaseID"].ToString());
                            foreach (DataRow dp in Paradt.Rows)
                            {
                                string paragraphText = dp["ParagraphText"].ToString();
                                int paragraphTypeId = Convert.ToInt32(dp["ParagraphTypeId"].ToString());
                                List<string> returnDic = paragraphtosentence.GetSentence(paragraphText, paragraphTypeId);

                                #region 句

                                foreach (string key in returnDic)
                                {
                                    Document doc = new Document();
                                    //添加doc  
                                    doc.Add(new Field("SentenceId", Guid.NewGuid().ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("SentenceTime", DateTime.Now.ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("Sentence", key, Field.Store.YES, Field.Index.ANALYZED)); //句
                                    doc.Add(new Field("ParagraphTypeId", paragraphTypeId.ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED)); //段150
                                    doc.Add(new Field("CaseId", dr["CaseID"].ToString(), Field.Store.YES,
                                        Field.Index.NOT_ANALYZED)); //caseid
                                    doc.Add(new Field("PropertyId", dr["PropertyId"].ToString(), Field.Store.NO,
                                        Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("JudicialProcedureId", dr["JudicialProcedureId"].ToString(),
                                        Field.Store.NO, Field.Index.NOT_ANALYZED));
                                    doc.Add(new Field("CourtId", dr["CourtId"].ToString(), Field.Store.NO,
                                        Field.Index.NOT_ANALYZED));
                                    //案由
                                    for (int k = 0; k < dtHeadWord.Rows.Count; k++)
                                    {
                                        doc.Add(new Field("AllParentID",
                                            dtHeadWord.Rows[k]["HW_AllParentIDs"].ToString(), Field.Store.NO,
                                            Field.Index.NOT_ANALYZED));
                                    }
                                    writer.AddDocument(doc);
                                }

                                #endregion
                            }

                            createIndex.UpdateIndexStatus(int.Parse(dr["CaseId"].ToString()));
                            _resultCount++;
                            processShow(MaxCount, _resultCount);

                        }

                        writer.Optimize();
                        writer.Commit();
                        writer.Dispose();
                        tran.Complete();


                        #endregion

                    }


                    if (_resultCount < MaxCount) //循环
                    {
                        CreateCaseIndex(cateGoryId);

                    }
                    else //不循环
                    {
                        _resultCount = MaxCount + 1;
                        processShow(MaxCount, _resultCount); //已完成
                        writer.Dispose();


                    }
                }
                else //不循环
                {
                    _resultCount = MaxCount + 1;
                    processShow(MaxCount, _resultCount); //已完成
                    writer.Dispose();

                }
            }
            catch (Exception ex)
            {
                AddLog.WriteLog(ex, "");
            }
            finally
            {
                writer.Dispose();
            }
        }

        #endregion


    }
}
